package com.helsinki.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.helsinki.mapper.PermissionMapper;
import com.helsinki.mapper.RoleMapper;
import com.helsinki.pojo.Permission;
import com.helsinki.pojo.Role;
import com.helsinki.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Override
    public PageInfo<Role> queryAll(Integer pageNum, Integer pageSize) {
        // 只有在要分页的查询之前才能设置分页信息
        PageHelper.startPage(pageNum, pageSize);
        List<Role> list = roleMapper.findAll();
        // PageInfo 封装了所有的分页信息
        return new PageInfo<>(list);
    }

    @Override
    public List<Role> findAll() {
        // 只有在要分页的查询之前才能设置分页信息
        List<Role> list = roleMapper.findAll();
        // PageInfo 封装了所有的分页信息
        return list;
    }
    @Override
    public void addRole(Role role) {
        UUID uuid = UUID.randomUUID();
        role.setId(uuid.toString().replaceAll("\\-", ""));

        roleMapper.addRole(role);
    }

    @Override
    public void updateRole(Role role) {
        roleMapper.updateById(role);
    }

    @Override
    public Role queryById(String id) {
        Role role = roleMapper.queryById(id);
        List<Permission> per = permissionMapper.findByRid(id);
        role.setPermissions(per);
        return role;
    }

    @Override
    public void updateRolePermission(Role role) {
        roleMapper.closeForeignKey();
        String id= role.getId();
        List<String> PIds = role.getSelect();
        roleMapper.deletePermissionByRid(id);
        for (String pId : PIds) {
            if (!pId.isEmpty()) {
                roleMapper.insertPermissionByRid(pId, id);
            }
        }
        roleMapper.openForeignKey();
    }

    @Override
    public Boolean deleteById(String id) {
        List<String> uid = roleMapper.findUserByRId(id);
        if(uid.isEmpty()){
             roleMapper.closeForeignKey();
             roleMapper.deleteById(id);
             roleMapper.deletePermissionByRid(id);
             roleMapper.openForeignKey();
             return true;
         }else {
             return false;
         }
    }
}
